'use strict'
import React, {useState} from 'react'
// prettier-ignore
import {
  StyleSheet,
  Text,
  View,
  Image,
  Animated,
  ScrollView,
} from 'react-native'

import RxClick from '../button/RxClick'

const RxDynamicScroll = props => {
  const [scrollViewWidth, setScrollViewWidth] = useState(0) // Scroll 控件宽度
  // const [offsetx, setOffsetx] = useState(0) // Scroll-offsetx
  const [textWidth, setTextWidth] = useState(0) // scroll->text 宽度

  let scrollTimer = null
  let scrollAfTimer = null

  let scrollAnimated = null
  let offsetx = React.useRef(new Animated.Value(0)).current

  const _stopAnimal = () => {
    // console.log('_stopAnimal')
    scrollTimer && clearInterval(scrollTimer)
    scrollTimer = null

    scrollAnimated && scrollAnimated.stop()
  }

  const _stopAllAnimal = () => {
    // console.log('_stopAllAnimal')
    scrollTimer && clearInterval(scrollTimer)
    scrollTimer = null

    scrollAnimated && scrollAnimated.stop()

    scrollAfTimer && clearTimeout(scrollAfTimer)
    scrollAfTimer = null
  }

  const _aferAnimal = fn => {
    // console.log('_aferAnimal')
    _stopAllAnimal()
    scrollAfTimer = setTimeout(() => {
      if (fn && typeof fn === 'function') {
        // console.log('_aferAnimal -- do fn')
        fn()
      }
    }, 500)
  }

  const _startAnimal = () => {
    if (scrollAnimated) {
      _stopAnimal()
    }

    if (textWidth === 0) {
      return
    }
    offsetx = new Animated.Value(textWidth)
    const maxValue = textWidth * -2
    console.log('start animal textWidth=', textWidth)
    scrollAnimated = Animated.timing(offsetx, {
      toValue: maxValue,
      duration: 3000,
      useNativeDriver: false,
    }).start(() => {
      console.log('scrollAnimated.stop..')
      _aferAnimal(() => {
        _startAnimal()
      })
    })

    // const maxWidth = textWidth - scrollViewWidth
    // let difference = offsetx - 1
    // // console.log('offsetx=', offsetx)
    // // console.log('_startAnimal maxWidth=', maxWidth, ' difference=', difference)
    // if (Math.abs(difference) > maxWidth) {
    //   // console.log('取消')
    //   _stopAnimal()
    //   return
    // }
    // let x = offsetx
    // scrollTimer = setInterval(() => {
    //   // console.log('_startAnimal - do setInterval')
    //   difference = x - 1
    //   // console.log('------------ difference=', difference, ' maxWidth=', maxWidth)
    //   if (Math.abs(difference) > maxWidth) {
    //     // console.log('_startAnimal --- _aferAnimal')
    //     _aferAnimal(() => {
    //       _startAnimal()
    //     })
    //   } else {
    //     requestAnimationFrame(() => {
    //       // console.log('_startAnimal --- setOffsetx')
    //       setOffsetx(difference)
    //     })
    //   }
    //   x = difference
    // }, 20)
  }

  console.log('offsetx=', offsetx)

  const {style, txts, icon} = props
  return (
    <View style={[styles.container, style]}>
      <View
        style={styles.content}
        onLayout={e => {
          const sw = Math.ceil(e.nativeEvent.layout.width)
          if (sw !== scrollViewWidth) {
            console.log('---scrollViewWidth=', sw)
            _stopAnimal()
            setScrollViewWidth(sw)
            _aferAnimal(() => {
              _startAnimal()
            })
          }
        }}>
        <ScrollView
          horizontal={true}
          scrollEnabled={true}
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.textContainer}
          style={{flex: 1}}>
            {/* style={[styles.text, {transform: [{translateX: offsetx}]}]} */}
          <Animated.Text
            numberOfLines={1}
            style={[styles.text, {left:  offsetx}]}
            onLayout={e => {
              let tw = Math.ceil(e.nativeEvent.layout.width)
              if (tw !== textWidth) {
                console.log('---textWidth=', tw)
                _stopAnimal()
                setTextWidth(tw)
                _aferAnimal(() => {
                  _startAnimal()
                })
              }
            }}>
            {txts}
          </Animated.Text>
        </ScrollView>
        <CloseBtn icon={icon} />
      </View>
    </View>
  )
}

const CloseBtn = (icon, cb) => {
  if (!icon) return null
  const b = () => {}
  cb = cb || b
  return (
    <RxClick onPress={cb}>
      <Image source={icon} />
    </RxClick>
  )
}

export default RxDynamicScroll

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 10,
    margin: 0,
  },
  content: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    margin: 0,
    padding: 0,
  },
  textContainer: {
    margin: 0,
    height: 32,
    alignItems: 'center',
  },
  text: {
    fontSize: 14,
    color: '#FC8936',
    lineHeight: 32,
  },
})
